package com.example.securitydemo.controllers;

import com.example.core.libs.JSONResult;
import com.example.securitydemo.form.LoginForm;
import com.example.securitydemo.services.IUserService;
import com.example.securitydemo.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @Autowired
    IUserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenUtils tokenUtils;

    @RequestMapping("/login")
    public JSONResult login(@RequestBody LoginForm form) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(form.getUserName(), form.getUserPassword());
        //执行登录
        String token = "";
        try {
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            //认证成功存储认证信息到上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            //生成token
            token = tokenUtils.generateToken(authentication);
        } catch (BadCredentialsException badCredentialsException) {
            return new JSONResult(-1, "用户或者账号密码错误");
        } catch (DisabledException disabledException) {
            return new JSONResult(-2, "此账户已被禁用");
        } catch (Exception e) {
            return new JSONResult(-3, "未知错误");
        }
        return new JSONResult().put("token", token);
    }

    @RequestMapping("/index")
    public JSONResult index() {
        return new JSONResult("欢迎来到首页");
    }

    @RequestMapping("/list")
    @Secured("ROLE_USER:VIEW")
    public JSONResult list() {
        return new JSONResult().put("list", userService.list());
    }

    @RequestMapping("/add")
    @Secured("ROLE_USER:ADD")
    public JSONResult add() {
        return new JSONResult("新增成功");
    }

    @RequestMapping("/unauthorized")
    public JSONResult unauthorized() {
        return new JSONResult("您还有权限哦");
    }

    @RequestMapping("/test")
    public JSONResult test() {
        return new JSONResult("test");
    }
}
